import { HashService } from '@app/hash';
import { PrismaService } from '@app/prisma';
import { ScienceEntity } from '@app/prisma/science.entity/science.entity';
import { ForbiddenError } from '@nestjs/apollo';
import { UseGuards } from '@nestjs/common';
import { Args, Int, Mutation, Resolver } from '@nestjs/graphql';
import { GqlAuthPowerGuard, AccountPower } from 'src/auth/auth.guard';

@Resolver()
export class ScienceResolver {
    constructor(
        private readonly prisma: PrismaService,
        private readonly hashService: HashService
    ) { }

    @Mutation(() => ScienceEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async addScience(
        @Args("departmentId", { type: () => Int }) departmentId: number,
        @Args("name") name: string
    ) {
        const dept = await this.prisma.department.findUnique({ where: { id: departmentId } })
        if (!dept) throw new ForbiddenError("404")
        return await this.prisma.science.create({
            data: {
                department: {
                    connect: {
                        id: dept.id
                    },
                },
                name,
                hash: this.hashService.cryptoIdAndName(
                    dept.id,
                    name
                )
            }
        })
    }

    @Mutation(() => ScienceEntity, { nullable: true })
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    delScience(
        @Args("id", { type: () => Int }) id: number
    ) {
        return this.prisma.science.delete({
            where: {
                id
            }
        })
    }

    @Mutation(() => ScienceEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async updScience(
        @Args("departmentId", { type: () => Int }) departmentId: number,
        @Args("name") name: string,
        @Args("id", { type: () => Int }) id: number
    ) {
        const dept = await this.prisma.department.findUnique({ where: { id: departmentId } })
        if (!dept) throw new ForbiddenError("404")
        return await this.prisma.science.update({
            where: {
                id
            },
            data: {
                department: {
                    connect: {
                        id: dept.id
                    },
                },
                name,
                hash: this.hashService.cryptoIdAndName(
                    dept.id,
                    name
                )
            }
        })
    }
}
